<template>
    <view class="mine-class">
        <!-- 顶部 -->
        <m-mine-header></m-mine-header>
        <m-mine-data></m-mine-data>
        <view class="m-style-2">
            <view class="nav flex-c">
                <view class="nav-l">导出</view>
            </view>
            <view class="list flex-c">
                <view class="list-item" v-for="(item, index) in mine_list_2" :key="index">
                    <button class="u-reset-button" open-type="contact" v-if="item.url == 'button'">
                        <view class="list-item-img" style="">
                            <image class="" style="width: 100%" :src="'../../static/mine/' + item.icon" mode="widthFix"></image>
                        </view>
                        <view class="list-item-text">
                            {{ item.name }}
                        </view>
                    </button>
                    <view v-else @click="jumpOrder(item)">
                        <view class="list-item-img" style="">
                            <image class="" style="width: 100%" :src="'../../static/mine/' + item.icon" mode="widthFix"></image>
                        </view>
                        <view class="list-item-text">
                            {{ item.name }}
                        </view>
                    </view>
                </view>
            </view>

            <view class="nav flex-c">
                <view class="nav-l">导入</view>
            </view>
            <view class="list flex-c">
                <view class="list-item" v-for="(item, index) in mine_list_3" :key="index">
                    <button class="u-reset-button" open-type="contact" v-if="item.url == 'button'">
                        <view class="list-item-img" style="">
                            <image class="" style="width: 100%" :src="'../../static/mine/' + item.icon" mode="widthFix"></image>
                        </view>
                        <view class="list-item-text">
                            {{ item.name }}
                        </view>
                    </button>
                    <view v-else @click="jumpOrder(item)">
                        <view class="list-item-img" style="">
                            <image class="" style="width: 100%" :src="'../../static/mine/' + item.icon" mode="widthFix"></image>
                        </view>
                        <view class="list-item-text">
                            {{ item.name }}
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <view style="text-align: center; font-weight: bold; margin: 30rpx">版本号:{{ $APP_VERSION }}</view>
        <a-tabbar path="pages/tabbar/mine"></a-tabbar>
    </view>
</template>
<script setup>
import * as XLSX from 'xlsx';
import { ref, watch } from 'vue';
import { onShow, onLoad } from '@dcloudio/uni-app';
onLoad(() => {
});
import data from '@/common/base/data.js';
const list = ref(data.mine_list_1);
const DATA_STORE = uni.$store('data');
const mine_list_2 = ref(data.mine_list_2);
const mine_list_3 = ref(data.mine_list_3);
const jumpOrder = (item) => {
    if (item.url == 'export_study') {
        tableToExcelBystudy(item);
    }
    if (item.url == 'export_log') {
        tableToExcelBylog(item);
    }
    if (item.url == 'import_study') {
        uni.$u.route('pages/web-view', {
            src: encodeURIComponent('/static/hybrid/html/index.html')
        });
        // plus.io.chooseFile(
        //     {
        //         title: '选择Excel文件',
        //         multiple: false
        //     },
        //     function (e) {
        //         var filePath = e.files[0];
        //         readExcelFile(filePath.split('/storage/emulated/0')[1]);
        //     }
        // );
    }
    if (item.url == 'import_log') {
        uni.$u.route('pages/web-view', {
            src: encodeURIComponent('/static/hybrid/html/index.html')
        });
    }
};
const readExcelFile = (fileEntryURL) => {
    console.log('选择的文件路径:', fileEntryURL);
    plus.io.resolveLocalFileSystemURL(
        fileEntryURL,
        function (entry) {
            entry.file(
                function (file) {
                    // 3. 创建 FileReader 并读取为 ArrayBuffer
                    var fileReader = new plus.io.FileReader();
                    console.log('fileReader: ' + JSON.stringify(fileReader));
                    fileReader.onloadend = function (evt) {
                        const arrayBuffer = evt.target.result;
                        // 4. 使用 SheetJS 解析 ArrayBuffer
                        const workbook = XLSX.read(arrayBuffer, { type: 'binary' });
                        console.log('解析到的Excel数据:', workbook);
                        const firstSheetName = workbook.SheetNames[0];
                        const worksheet = workbook.Sheets[firstSheetName];
                        const jsonData = XLSX.utils.sheet_to_json(worksheet);

                        console.log('解析到的Excel数据:', jsonData);
                        // 在这里处理解析后的 jsonData
                    };
                    fileReader.onerror = function (error) {
                        console.log('failed: ', error);
                    };
                    fileReader.readAsDataURL(file);
                    // reader.onloadend = function (evt) {
                    //     const arrayBuffer = evt.target.result;
                    //     // 4. 使用 SheetJS 解析 ArrayBuffer
                    //     const workbook = XLSX.read(arrayBuffer, { type: 'array' });
                    //     const firstSheetName = workbook.SheetNames[0];
                    //     const worksheet = workbook.Sheets[firstSheetName];
                    //     const jsonData = XLSX.utils.sheet_to_json(worksheet);

                    //     console.log('解析到的Excel数据:', jsonData);
                    //     // 在这里处理解析后的 jsonData
                    // };
                    // reader.onerror = function (error) {
                    //     console.error('读取失败:', error);
                    // };
                    // reader.readAsArrayBuffer(file); // 读取为 ArrayBuffer
                },
                function (error) {
                    console.error('获取File对象失败:', error);
                }
            );
        },
        function (error) {
            console.error('解析文件路径失败:', error);
        }
    );
};
// =========================================================================================

const tableToExcelBylog = (item) => {
    //要导出的json数据
    const jsonData = uni.getStorageSync('BalanceList');
    if (!jsonData || jsonData.length == 0) return uni.$u.toast('暂无数据');
    // *姓名 id  *卡内余额 动账金额 动账方式  时间   体育项目 备注
    //     name,
    //     id,
    //     balance
    //     type,
    //     ctime: form_data.ctime,
    //     money: form_data.money,
    //     note: form_data.note,
    //     typeText: form_data.typeText
    //列标题
    let worksheet = 'sheet1';
    let str = '<tr><td>id</td><td>姓名</td><td>卡内余额</td><td>动账类型(1加 0减)</td><td>动账时间</td><td>动账金额</td><td>备注</td><td>签到类型</td></tr>';
    //循环遍历，每行加入tr标签，每个单元格加td标签
    for (let i = 0; i < jsonData.length; i++) {
        str += '<tr>';
        let { id, name, balance, type, ctime, money, note = '', typeText = '' } = jsonData[i];
        str += `<td>${id}</td><td>${name}</td><td>${balance}</td><td>${type}</td><td>${ctime}</td><td>${money}</td><td>${note}</td><td>${typeText}</td>`;
        str += '</tr>';
    }

    //下载模板

    exportFile({ worksheet, str }, 'log_list', item);
};
const tableToExcelBystudy = (item) => {
    //要导出的json数据
    const jsonData = uni.getStorageSync('studentList');
    if (!jsonData || jsonData.length == 0) return uni.$u.toast('暂无数据');
    // id: '', //id
    //   name: '', //姓名
    //   balance: '', //卡内余额
    //   birthday: '', //生日
    //   sex: '男', //性别
    //   phone: '', //联系方式
    //   emergencyContactPerson: '', //紧急联系人
    //   address: '', //家庭住址
    //   note: '' //备注
    //列标题
    let worksheet = 'sheet1';
    let str = '<tr><td>id</td><td>姓名</td><td>卡内余额</td><td>生日</td><td>性别</td><td>联系方式</td><td>紧急联系人</td><td>家庭住址</td><td>备注</td></tr>';
    //循环遍历，每行加入tr标签，每个单元格加td标签
    for (let i = 0; i < jsonData.length; i++) {
        str += '<tr>';
        let { id, name, balance, birthday, sex, phone, emergencyContactPerson, address, note } = jsonData[i];
        str += `<td>${id}</td><td>${name}</td><td>${balance}</td><td>${birthday}</td><td>${sex}</td><td>${phone}</td><td>${emergencyContactPerson}</td><td>${address}</td><td>${note}</td>`;
        str += '</tr>';
    }

    //下载模板

    exportFile({ worksheet, str }, 'student_list', item);
};
function exportFile(obj, documentName, item) {
    /*
        PRIVATE_DOC: 应用私有文档目录常量
        PUBLIC_DOCUMENTS: 程序公用文档目录常量
        */
    //下载的表格模板数据
    let fileData = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
        xmlns:x="urn:schemas-microsoft-com:office:excel"
        xmlns="http://www.w3.org/TR/REC-html40">
        <head><!--[if gte mso 9]><xml encoding="UTF-8"><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
        <x:Name>${obj.worksheet}</x:Name>
        <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
        </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
        </head><body><table>${obj.str}</table></body></html>`;
    plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function (fs) {
        let rootObj = fs.root;
        let fullPath = rootObj.fullPath;
        let reader = rootObj.createReader();
        // 创建文件夹
        rootObj.getDirectory(
            documentName,
            {
                create: true
            },
            function (dirEntry) {
                //获取当前的年月继续创建文件夹
                let date = new Date();
                let year = date.getFullYear();
                let month = date.getMonth() + 1;
                dirEntry.getDirectory(
                    `${year}_${month}`,
                    {
                        create: true
                    },
                    function (dirEntry2) {
                        // 创建文件,防止重名
                        let fileName = uni.$u.timeFormat(new Date().getTime(), 'yyyy-mm-dd_hh-MM-ss');
                        dirEntry2.getFile(
                            `${fileName}.xlsx`,
                            {
                                create: true
                            },
                            function (fileEntry) {
                                fileEntry.createWriter(
                                    function (writer) {
                                        writer.onwritestart = (e) => {
                                            uni.showLoading({
                                                title: '正在导出',
                                                mask: true
                                            });
                                        };

                                        //  /storage/emulated/0指的就是系统路径
                                        let pathStr = fullPath.replace('/storage/emulated/0', '');
                                        writer.onwrite = (e) => {
                                            // 成功导出数据;
                                            uni.hideLoading();
                                            setTimeout(() => {
                                                uni.showToast({
                                                    title: '成功导出',
                                                    icon: 'success'
                                                });
                                                uni.showModal({
                                                    title: '文件存放位置:',
                                                    content: `文件位置：${pathStr}/${documentName}/${year}_${month}`,
                                                    showCancel: false
                                                });
                                            }, 500);
                                        };
                                        // 写入内容;
                                        writer.write(fileData);
                                    },
                                    function (e) {
                                        console.log(e.message);
                                    }
                                );
                            }
                        );
                    }
                );
            }
        );
    });
}
</script>
<style scoped lang="scss">
.m-style-1 {
    position: relative;
    background: #ffffff;
    padding: 24rpx 0 22rpx;
    margin-bottom: 26rpx;
    width: 718rpx;
    border-radius: 8rpx 8rpx 8rpx 8rpx;
    margin: 0 auto 16rpx;

    .nav {
        padding: 0 24rpx 20rpx 24rpx;

        .nav-l {
            font-family: PingFang SC, PingFang SC;
            font-weight: 600;
            font-size: 34rpx;
            line-height: 33rpx;
            color: #2b2b2b;
            margin-right: 14rpx;
        }
    }

    .lawyer_class {
        padding: 0 100rpx !important;
    }

    .list {
        padding: 0 78rpx;

        .list-item {
            .list-item-img {
                margin: 0 auto;
                width: 60rpx;
                height: 66rpx;
            }

            .list-item-text {
                font-family: PingFang SC, PingFang SC;
                font-size: 24rpx;
                color: #666666;
                text-align: center;
                line-height: 28rpx;
            }
        }
    }
}

.m-style-2 {
    background: #ffffff;
    padding: 24rpx 0 0;
    margin-bottom: 26rpx;
    width: 718rpx;
    border-radius: 8rpx 8rpx 8rpx 8rpx;
    margin: 0 auto 0;

    .nav {
        padding: 0 24rpx 20rpx 24rpx;

        .nav-l {
            font-family: PingFang SC, PingFang SC;
            font-weight: 600;
            font-size: 38rpx;
            line-height: 1.4;
            color: #2b2b2b;
            margin-right: 14rpx;
        }
    }

    .list {
        flex-wrap: wrap;

        .list-item {
            width: 33%;
            margin-bottom: 32rpx;

            .list-item-img {
                margin: 0 auto;
                width: 60rpx;
                height: 66rpx;
            }

            .list-item-text {
                font-family: PingFang SC, PingFang SC;
                font-size: 34rpx;
                color: #666666;
                text-align: center;
                line-height: 1.4;
            }
        }
    }
}
</style>
